//
//  M_PartIndexVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/18.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MJRefresh

class M_PartIndexVC: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    var pageIndex = 1
    var pageCount = 1
    var sortType = 2
    let topImg = Button()
    let bannerImg = BannerUseScrollView()
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    
    var headList = [String: Any?]()
    var bannerList = [[String: Any?]]()
    var arcList = [[String: Any?]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        reloadAll()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    
    func getLatestSysarticle(callback: @escaping (Bool,[String:Any?]) -> Void) {
        let dic = LocalStorage.getDic(forKey: DEFULT_MALL)
        let params :[String:Any] = ["mallID": dic?.getString("mallID") ?? ""]
        API.formRequest(url: .YI_GetLatestSysarticle, params: params) { (result) in
            if let dl = result.data?.getDictionary("data") {
             callback(result.success,dl)
            }
        }
    }
    
    func getFocusSysarticleList(callback: @escaping (Bool,[[String:Any?]]) -> Void) {
        let dic = LocalStorage.getDic(forKey: DEFULT_MALL)
        let params :[String:Any] = ["pageIndex": 1,
                                    "mallID": dic?.getString("mallID") ?? ""]
        API.formRequest(url: .YI_GetFocusSysarticleList, params: params) { (result) in
            if let dl = result.data?.getDictList("data") {
             callback(result.success,dl)
            }
        }
    }
    
    func getPastSysarticleList(callback: @escaping (Bool,[[String:Any?]]) -> Void) {
        let dic = LocalStorage.getDic(forKey: DEFULT_MALL)
        let params :[String:Any] = ["pageIndex": pageIndex,
                                    "mallID": dic?.getString("mallID") ?? "",
                                    "sortType": sortType]
        API.formRequest(url: .YI_GetPastSysarticleList, params: params) { (result) in
            
            self.pageCount = result.data?.getInt("pageCount") ?? 1
            self.pageIndex = result.data?.getInt("pageIndex") ?? 1
            if let dl = result.data?.getDictList("data") {
             callback(result.success,dl)
            }
        }
    }
    
}

// MARK:- UI
extension M_PartIndexVC {
    func setupUI() {
        
        headView.drawImage(named: "lepaidui_2") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton.snp.centerY)
        }
        backButton.isHidden = true
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        //画横线
        let line = headView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(1)
            make.height.equalTo(2)
        }
        line.backgroundColor = .xF2F2F2
        
        //添加列表
        let _ = getRefreshHeader()
        let _ = getRefreshFooter()
        tableView.backgroundColor = UIColor.white
        safeView.addSubview(tableView)
        tableView.register(M_PartIndexCell.self, forCellReuseIdentifier: "M_PartIndexCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 198
        tableView.rowHeight = UITableView.automaticDimension
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    func getRefreshHeader()->MJRefreshHeader {
//        顶部的下拉初始化
        let header = MJRefreshNormalHeader()
        header.lastUpdatedTimeLabel.isHidden = true
        tableView.mj_header = header
        header.setTitle("下拉刷新...", for: .idle)
        header.setTitle("下拉刷新...", for: .pulling)
        header.setTitle("下拉更新中...", for: .refreshing)
        header.setTitle("完成...", for: .willRefresh)
        header.setTitle("下拉刷新...", for: .noMoreData)
        header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

//        顶部的处理逻辑：
        return tableView.mj_header!
    }
    
    func getRefreshFooter()->MJRefreshFooter {
        if tableView.mj_footer == nil {
            //        底部初始化：
            let footer = MJRefreshBackNormalFooter()
//            footer.isOnlyRefreshPerDrag = true
            tableView.mj_footer = footer
            footer.setTitle("上拉加载更多...", for: .idle)
            footer.setTitle("上拉加载更多...", for: .pulling)
            footer.setTitle("下拉更新中...", for: .refreshing)
            footer.setTitle("完成...", for: .willRefresh)
            footer.setTitle("没有了...", for: .noMoreData)
            footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
        }

        //        底部处理逻辑：
        if pageIndex < pageCount {
            tableView.mj_footer.endRefreshing()
        }
        else {
            tableView.mj_footer.endRefreshingWithNoMoreData()
        }
//        底部数据加载
         return tableView.mj_footer!
    }
}

// MARK:- 事件
extension M_PartIndexVC {
    func reloadAll() {
                getLatestSysarticle(callback: { (_,data) in
                    self.headList = data
                    let urlAry = data.getString("imgs")?.components(separatedBy: ",")
                    if let url = urlAry?.first {
                        self.topImg.sd_setImage(with: URL(string: url), for: .normal)
                    }
                })
                
                getFocusSysarticleList(callback: { (_,data) in
                    self.bannerImg.backgroundColor = .white
                    self.bannerImg.images.removeAll()
                    self.bannerImg.urls.removeAll()
                    for i in 0...data.count-1 {
//                        let imgview = self.bannerImg.scrollView!.subviews[i] as? UIImageView
                        let urlAry = data[i].getString("imgs")?.components(separatedBy: ",")
                        let url = urlAry?.first ?? ""
                        self.bannerImg.urls.append(URL(string: url))
                    }
                    self.bannerImg.isLoadUrl = true
                    self.bannerImg.scrollView.removeFromSuperview()
                    self.bannerImg.pageView.removeFromSuperview()
                    self.bannerImg.removeTimer()
                    self.bannerList = data
                    if data.count < 2 {
                        self.bannerImg.isSignel = true
                    }
                    self.bannerImg.draw(self.bannerImg.frame)
                    self.bannerImg.callSelBlock(block: { (index) in
                        self.bannerOnClick(index: index)
                    })
                })
        //
                getPastSysarticleList(callback: { (_,data) in
                    self.arcList = data

                    self.tableView.reloadData()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute:{
                        self.tableView.reloadData()
                    })


                    //        底部数据重新加载更多底部处理逻辑：
                    if self.pageIndex < self.pageCount,self.arcList.count > 0 {
                        self.tableView.mj_footer.endRefreshing()
                    }
                    else {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                })
    }
    
    @objc func onHeaderRequery() {
        //        顶部数据重新加载
        getRefreshFooter().state = .idle
        tableView.mj_header.endRefreshing()
        tableView.reloadData()
    }
    
    @objc func onFooterLoadMore() {
        pageIndex += 1
        getPastSysarticleList(callback: { (_,data) in
            self.arcList.append(contentsOf: data)
            self.tableView.reloadData()

            //        底部数据重新加载更多底部处理逻辑：
            if self.pageIndex < self.pageCount,self.arcList.count > 0 {
                self.tableView.mj_footer.endRefreshing()
            }
            else {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
        })
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    
    @objc func _hotButtonClick(button: Button) {
        sortType = 2
        reloadAll()
    }
    
    @objc func _newButtonClick(button: Button) {
        sortType = 1
        reloadAll()
    }
    
    @objc func topImgOnClick(button: Button) {
        let vc = M_HuodongArticleVC()
        pushViewController(vc)
        print(headList)
        if let id = anyToString(headList.getInt("id")) {
            vc.artId = id
        }
        else if let html = headList.getString("content") {
            vc.loadString(html)
        }
        vc.dataDic = headList
        vc.headTitle.text = "活动推文"
    }
    
    func bannerOnClick(index: Int) {
        let vc = M_HuodongArticleVC()
        pushViewController(vc)
        if let id = anyToString(bannerList[index].getInt("id")) {
            vc.artId = id
        }
        else if let html = bannerList[index].getString("content") {
            vc.loadString(html)
        }
        vc.dataDic = bannerList[index]
        vc.headTitle.text = "活动推文"
    }
    
    ///MARK: UITableViewDelegate
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        let vc = M_HuodongArticleVC()
        pushViewController(vc)
        if let id = anyToString(arcList[indexPath.row].getInt("id")) {
            vc.artId = id
        }
        else if let html = arcList[indexPath.row].getString("content") {
            vc.loadString(html)
        }
        vc.dataDic = arcList[indexPath.row]
        vc.headTitle.text = "活动推文"
    }
    
    ///MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let thview = UIView()
        thview.backgroundColor = .white
        thview.drawView(view: topImg) { (make) in
            make.top.equalToSuperview().offset(10)
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-20)
            make.height.equalTo(190)
        }
        topImg.contentMode = .scaleAspectFit
        topImg.layer.cornerRadius = 5
        topImg.clipsToBounds = true
        let urlAry = headList.getString("imgs")?.components(separatedBy: ",")
        if let url = urlAry?.first {
            let u = URL(string: url)
            self.topImg.sd_setImage(with: u, for: .normal)
        }
        topImg.addTarget(self, action: #selector(topImgOnClick(button:)), for: .touchUpInside)
        
        bannerImg.images = [UIImage.createImageFrom(color: .white),UIImage.createImageFrom(color: .white),UIImage.createImageFrom(color: .white),UIImage.createImageFrom(color: .white)]
        bannerImg.imagewidth = 211.5
        bannerImg.imageheight = 107
        thview.drawView(view: bannerImg) { (make) in
            make.top.equalTo(topImg.snp.bottom).offset(10)
            make.width.equalToSuperview()
            make.height.equalTo(130)
        }
        
        //画横线
        let line = thview.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(bannerImg.snp.bottom).offset(10)
            make.height.equalTo(10)
        }
        line.backgroundColor = .xF2F2F2
        
        //画竖线
        let line2 = thview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(line.snp.bottom).offset(24)
            make.height.equalTo(13)
            make.width.equalTo(3)
        }
        line2.backgroundColor = .xFC4C02
        
        thview.drawLabel(text: "往期专栏", fontSize: 18, textColor: .x333333) { (make) in
            make.left.equalTo(line2.snp.right).offset(10)
            make.bottom.equalTo(line2.snp.bottom).offset(3)
        }
        if sortType == 2 {
            var btn = thview.drawButton(title:"最新", titleColor: .x999999, fontSize: 12) {(make) in
                make.bottom.equalToSuperview().offset(-10)
                make.right.equalToSuperview().offset(-10)
                make.width.equalTo(36)
                make.height.equalTo(18)
            }
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor.x999999.cgColor
            btn.layer.cornerRadius = 3
            btn.addTarget(self, action: #selector(_newButtonClick(button:)), for: .touchUpInside)
            
            btn = thview.drawButton(title:"最热", titleColor: .xFC4C02, fontSize: 12) {(make) in
                make.bottom.equalToSuperview().offset(-10)
                make.right.equalToSuperview().offset(-55)
                make.width.equalTo(36)
                make.height.equalTo(18)
            }
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor.xFC4C02.cgColor
            btn.layer.cornerRadius = 3;
            btn.addTarget(self, action: #selector(_hotButtonClick(button:)), for: .touchUpInside)
        }
        else {
            var btn = thview.drawButton(title:"最新", titleColor: .xFC4C02, fontSize: 12) {(make) in
                make.bottom.equalToSuperview().offset(-10)
                make.right.equalToSuperview().offset(-10)
                make.width.equalTo(36)
                make.height.equalTo(18)
            }
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor.xFC4C02.cgColor
            btn.layer.cornerRadius = 3
            btn.addTarget(self, action: #selector(_newButtonClick(button:)), for: .touchUpInside)
            
            btn = thview.drawButton(title:"最热", titleColor: .x999999, fontSize: 12) {(make) in
                make.bottom.equalToSuperview().offset(-10)
                make.right.equalToSuperview().offset(-55)
                make.width.equalTo(36)
                make.height.equalTo(18)
            }
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor.x999999.cgColor
            btn.layer.cornerRadius = 3;
            btn.addTarget(self, action: #selector(_hotButtonClick(button:)), for: .touchUpInside)
        }
        return thview
    }
    
    //头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 406.5
    }
    
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    // 设置cell高度
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 90
//    }
    
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arcList.count
    }
    
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "M_PartIndexCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_PartIndexCell
        if cell==nil {
            cell = M_PartIndexCell(style: .subtitle, reuseIdentifier: cellid)
        }
        
        cell?.celldata = arcList[indexPath.row]
        cell?.callShareBlock {
            UMSocialUIManager.setPreDefinePlatforms([NSNumber.init(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue), NSNumber.init(value: UMSocialPlatformType.wechatSession.rawValue)])
            UMSocialUIManager.addCustomPlatformWithoutFilted(UMSocialPlatformType(rawValue: 1001)!, withPlatformIcon: UIImage.init(named: "share_link"), withPlatformName: "复制链接")
            UMSocialUIManager.showShareMenuViewInWindow { (platform: UMSocialPlatformType, userInfo: [AnyHashable : Any]?) in
                if platform == UMSocialPlatformType(rawValue: 1001)! {
                    let pastboard = UIPasteboard.general
                    if let id = anyToString(self.arcList[indexPath.row].getInt("id")) {
                        pastboard.string = ARTICLE_URL + id
                    }

                    let popup = PopupBox(infoText: "已复制")
                    if let vc = UIViewController.topMostController() {
                        popup.show(vc: vc)
                    }
                    return
                }
                
                let messageObject = UMSocialMessageObject()
                let webMessageContent = UMShareWebpageObject.shareObject(withTitle: cell?.celldata?.getString("title"), descr: cell?.celldata?.getString("enterpriseName"), thumImage: cell?.mainImg.image ?? UIImage(named: "share_link2"))

                if let id = anyToString(self.arcList[indexPath.row].getInt("id")) {
                    webMessageContent?.webpageUrl = ARTICLE_URL + id
                }

                messageObject.shareObject = webMessageContent
                UMSocialManager.default()?.share(to: platform, messageObject: messageObject, currentViewController: self, completion: { (info, error) in
                    
                })
            }
        }
        return cell!
    }
}
